<template>
  <div>
    <van-nav-bar fixed title="聚合页面" left-arrow @click-left="$utils.back($route.path)" />
    <div class="has-top">
      <!-- 头部定位搜索导航组件 -->
    
<wx-open-launch-weapp id="launch-btn" appid="wx7b0bc76e858476e2"  username="gh_a195cb2482c4" path="pages/login/loading">
        <script type="text/wxtag-template">
                <style>
                    .label {
                        color: #448ce1;
                        font-size: 15px;
                        display:block;
                        text-align:center;
                         margin-top: 10px;
                        }
                <style>
            <div class="label">跳转小程序<div>
           
            </script>
        </wx-open-launch-weapp>

    </div>
  </div>
</template>

<script>
import imgBox from 'components/imgBox'
import physioSearch from 'components/physioSearch'
import areaSelect from 'components/areaSelect'
import bussinessItem from 'components/bussinessItem'
import noData from 'components/noData'
import { GetStorePage, GetStoreCategoryTree, GetStoreTagList, GetCityIdByCode, GetUserCityId } from 'api/store'

export default {
  components: {
    imgBox,
    physioSearch,
    areaSelect,
    bussinessItem,
    noData
  },
  data() {
    return {
      val: '',
      locationCity: {
        ID: 0,
        Name: '定位中...'
      },
      // 初始化定位flag
      locationInit: false,
      AreaSelect: false,
      tabs: [
          {
              value: '推荐',
              id: -1
          },
          {
              value: '跑得较快',
              id: 0
          },
          {
              value: '离我最近',
              id: 1
          },
          {
              value: '我的收藏',
              id: 2
          }
      ],
      tabsIndex: 0,
      activeId: 1,
      activeIndex: 0,

      // 中间排序
      value1: 1,
      option1: [
        { text: '综合排序', value: 1 },
        { text: '距离优先', value: 2 },
        { text: '销量优先', value: 3 }
      ],

      // 筛选条件
      value2: 0,
      option2: [{ text: '全部', value: 0 }],

      // 商家列表
      bussinessList: [],

      // 商家分页条件
      requestData: {
          state: -1,
          PageIndex: 1,
          PageSize: 10,
      }, // 列表查询

      // 下拉刷新
      loading: false, // 加载load
                finished: false, // 无更多数据
      isRefresh: false,
      animated: '',
      storeTypeList: [],
      // 允许列表加载(在定位成功或失败后设置true)
      listLoad: false,

      // 滚动状态
      totalAmout: 0,
      scollRequest: true,
      end: false,
      activeCategoryId:0
    }
  },
  beforeCreate () {
  	  // 例如设置为红色
      document.querySelector('body').setAttribute('style', 'background-color: #F2F3FC;')
  },
  beforeDestroy () {
      document.querySelector('body').removeAttribute('style')
  },
  mounted() {
    this.$nextTick(function() {
      window.addEventListener('scroll', this.onScroll)
    })
  },
  created() {
    console.log(this.$route)
    console.log(this.$route.query)
    const _query = this.$route.query
    if (_query && _query.storeName && _query.storeName !== 'undefined' && _query.storeName !== undefined) {
      this.val = _query.storeName
      this.recommendCondition.Name = _query.storeName
    }
    if(_query.CategoryId){
      this.activeCategoryId = _query.CategoryId
    }
    // 获取定位
    // 获取筛选标签
  },
  activated() {
    this.scollRequest = true
  },
  methods: {
    goDetail(item) {
      this.scollRequest = false
      console.log(item.ID)
      if(item.IndexUrl){
        window.location.href = item.IndexUrl
      }else{
        this.$router.push({
          path: '/businessDetail/' + item.ID
        })
      }
    },
    // 下拉刷新
    onRefresh() {
      if (this.listLoad) {
        this.isRefresh = true
        this.listLoad = false
        this.end = false
        this.recommendCondition.PageIndex = 1
        this.bussinessList = []
        if(this.activeCategoryId==0){
          this.GetStorePage()
        }
        // 获取分类列表
        // this.GetStoreCategoryTree({ 'regionName': this.locationCity.Name })
        this.GetStoreCategoryTree({ 'regionName': '' })
      } else {
        this.isLoading = false
      }
    },
    // 列表刷新后的回调
    listRefresh() {
      this.isRefresh = false
      this.isLoading = false
    },
    // 显示地址选择
    showAreaSelect(val) {
      console.log(val)
      const self = this
      self.animated = 'slideIn'
      self.AreaSelect = val
      setTimeout(() => {
        self.animated = ''
        ModalHelper.afterOpen()
      }, 300)
    },
    // 关闭地址选择
    closeAreaSelect(val) {
      const self = this
      self.animated = 'slideOut'
      setTimeout(() => {
        self.AreaSelect = val
        self.animated = ''
        ModalHelper.beforeClose()
      }, 300)
    },
    // 选择城市回调
    selCity(item) {
      console.log(item)
      if (this.locationCity.ID !== item.ID) {
        this.locationCity.ID = item.ID
        this.locationCity.Name = item.Name
        // 手动选择城市后不再进行定位初始化
        const _str = JSON.stringify(item)
        localStorage.setItem('SelectCity', _str)
        this.locationInit = true
        this.listLoad = true
        this.recommendCondition.areaId = item.ID
        this.onRefresh()
      }
    },
    // 关键字搜索商户列表
    search(key) {
      this.recommendCondition.PageIndex = 1
      this.recommendCondition.Name = key
      this.bussinessList = []
      this.GetStorePage()
    },

    // 获取缓存定位
    getLocalPosition() {

    },
    // 监听定位
    getCurrentPosition(cityName) {
      const _this = this
      // 对查询条件经纬度赋值0 0
      delete _this.recommendCondition.Lng
      delete _this.recommendCondition.Lat

      _this.locationCity.Name = cityName || '定位中...'
      _this.locationInit = !!cityName
      console.log(_this.locationInit)
      this.$toast.loading({
        forbidClick: true,
        message: 'loading...',
        loadingType: 'spinner',
        duration: 0
      })
      _this.$geolocation.getCurrentPosition(function(status, result) {
        if (status === 'complete') {
          _this.onComplete(result)
        } else {
          _this.onError(result)
        }
      })
    },

    // 精准定位成功
    onComplete(data) {
      console.log('精准定位成功')
      console.log(data)
      localStorage.setItem('GeolocationData', JSON.stringify(data))
      this.$toast.clear()
      this.closeAreaSelect(false)
      // 对查询条件经纬度赋值
      this.recommendCondition.Lng = data.position.lng
      this.recommendCondition.Lat = data.position.lat
      if (!this.locationInit) {
        this.locationCity.Name = data.addressComponent.district || data.addressComponent.city
        const adcode = parseInt(data.addressComponent.adcode.substr(0, 4) + '00').toString()
        this.GetCityIdByCode(adcode)
      } else {
        this.listLoad = true
        this.isRefresh = true
        this.onRefresh()
      }
    },
    // 精准定位失败
    onError(data) {
      console.log('精准定位失败')
      const _this = this
      _this.$geolocation.getCityInfo(function(status, result) {
        if (status === 'complete') {
          _this.onComplete1(result)
        } else {
          _this.onError1(result)
        }
      })
    },
    // ip定位成功
    onComplete1(data) {
      console.log('ip定位成功')
      console.log(data)
      localStorage.setItem('GeolocationData', JSON.stringify(data))
      this.$toast.clear()
      this.closeAreaSelect(false)
      // 对查询条件经纬度赋值
      this.recommendCondition.Lng = data.center[0]
      this.recommendCondition.Lat = data.center[1]
      // 第一次初始化定位城市
      if (!this.locationInit) {
        this.locationCity.Name = data.city
        const adcode = parseInt(data.adcode.substr(0, 4) + '00').toString()
        this.GetCityIdByCode(adcode)
      } else {
        this.listLoad = true
        this.isRefresh = true
        this.onRefresh()
      }
    },
    // ip定位失败
    onError1(data) {
      console.log('ip定位失败')
      console.log(data)
      this.$toast.clear()
      this.$toast.fail({
        message: '获取定位信息失败，请刷新',
        icon: 'close'
      })
      this.locationCity.Name = '未知'
      setTimeout(() => {
        if (!this.locationInit) {
          this.locationInit = true
          this.listLoad = true
          this.isRefresh = true
          this.onRefresh()
        }
      }, 1000)
    },
    chose(data) {
      console.log(data)
      this.value0 = data.text
      this.$refs.item.toggle()
      this.recommendCondition.CategoryId = data.id
      console.log(this.recommendCondition)
      this.bussinessList = []
      this.GetStorePage()
    },
    change1(ID) {
      console.log(ID)
      this.recommendCondition.OrderBy = ID
      this.bussinessList = []
      this.GetStorePage()
    },
    change2(ID) {
      console.log(ID)
      this.recommendCondition.TagId = ID
      this.bussinessList = []
      this.GetStorePage()
    },

    // 获取分类列表
    GetStoreCategoryTree(data) {
      GetStoreCategoryTree(data).then(res => {
        if (res) {
          console.log(res.Data)
          if (res.Data && res.Data.children) {
            this.items = res.Data.children
            this.items.forEach(item => {
                var _obj = {}
                _obj.text = '全部'
                _obj.id = item.id
                _obj.children = []
                item.children.unshift(_obj)
            })
          }
          const _total = {}
          _total.text = res.Data.text
          _total.id = res.Data.id
          _total.children = []
          const _childrenItem = {}
          _childrenItem.text = res.Data.text
          _childrenItem.id = res.Data.id
          _total.children.push(_childrenItem)
          this.items.unshift(_total)
          if(this.activeCategoryId > 0){
            this.items.forEach(rsp => {
              if(rsp.id == this.activeCategoryId){
                this.value0 = rsp.text
                this.recommendCondition.CategoryId = rsp.id
                this.bussinessList = []
                this.GetStorePage()
                this.activeCategoryId = 0
                return
              }else{
                rsp.children.forEach(subrsp =>{
                  if(subrsp.id == this.activeCategoryId){
                    this.value0 = subrsp.text
                    this.recommendCondition.CategoryId = subrsp.id
                    this.bussinessList = []
                    this.GetStorePage()
                    this.activeCategoryId = 0
                    return
                  }
                })
              }
            })
          }
        }
      })
    },
    // 获取筛选列表
    GetStoreTagList() {
      GetStoreTagList().then(res => {
        if (res) {
          console.log(res)

          // 添加全部选项
          const _total = {}
          _total.text = '全部'
          _total.value = 0

          this.option2 = res.Data.map((item, index, ary) => {
            const _item = {}
            _item.text = item.Name
            _item.value = item.ID
            return _item
          })
          this.option2.unshift(_total)
        }
      })
    },
    // 获取商家分页
    GetStorePage() {
      GetStorePage(this.recommendCondition).then(res => {
        if (res) {
          console.log(res)
          if (res.Data.length && res.Data.length > 0) {
            res.Data.forEach(tem => {
              if (!tem.Logo && tem.ShopSign) {
                tem.Logo = tem.ShopSign.split(',')[0]
              }
              this.bussinessList.push(tem)
            })
          }
          console.log(this.bussinessList)
          this.totalAmout = res.TotalAmout
          this.scollRequest = true
          this.listLoad = true
          this.isLoading = false
        }
      })
    },
    // 获取城市id
    GetCityIdByCode(code) {
      GetCityIdByCode({ RegionCode: code }).then(res => {
        if (res) {
          this.locationCity.ID = res.Data

          this.recommendCondition.areaId = res.Data
          const _str = JSON.stringify(this.locationCity)
          localStorage.setItem('SelectCity', _str)
          // 初始化请求参数
          this.recommendCondition.PageIndex = 1
          this.bussinessList = []
          // 获取商家列表
          this.GetStorePage()
          // 获取分类列表
          this.GetStoreCategoryTree({ 'regionName': this.locationCity.Name })
        }
      })
    },
    // 获取所属区域
    GetUserCityId() {
      GetUserCityId().then(res => {
        if (res && res.Data) {
          if (res.Data.ID === 0) {
            this.getCurrentPosition()
          } else {
            const _str = JSON.stringify(res.Data)
            localStorage.setItem('SelectCity', _str)
            this.getPosition()
          }
        }
      })
    },
    // 滚动事件触发下拉加载
    onScroll() {
      const _this = this
      if (_this.scollRequest === true) {
        if (_this.$utils.getScrollHeight() - _this.$utils.getClientHeight() - _this.$utils.getScrollTop() <= 5) {
          _this.scollRequest = false
          if (_this.recommendCondition.PageIndex < _this.totalAmout) {
            _this.recommendCondition.PageIndex++
            _this.GetStorePage()
          } else {
            _this.end = true
          }
          // }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.title{
  background: #F2F3FC;
}
.tab{
  div{
    padding-right: 48px;
    font-weight: bold;
    color: #7D8699;
    font-size: 32px;

  }
  .active{
    font-size: 36px;
    color: #2A2D33;
  }
}
.index-type {
  background: $colorBg;
}
.index-type-item {
  width: 20%;
  .van-image {
    width: 56px;
    height: 56px;
  }
}
.van-hairline--bottom::after {
  border-bottom: none;
}
/deep/.van-dropdown-menu__title .van-ellipsis {
  max-width: 70px;
  font-size: 13px;
}
.fw{
  width: 108px;
  height: 36px;
  background: linear-gradient(180deg, #AC92FF 0%, #7459FF 100%);
  border-radius: 16px 8px 16px 8px;
  border: 1px solid;
}
</style>
